<template>
    <div>
        <el-form class="demo-form-inline" :model="queryForm">
            <el-form-item label="接口编码">
                <el-input v-model="queryForm.code" placeholder="接口代码" :disabled="!codeEditable"></el-input>
            </el-form-item>
            <el-form-item label="接口参数">
                <el-button type="text" icon="el-icon-edit"
                    @click="showJsonFormat = !showJsonFormat">{{ showJsonFormat ? '表格' : 'JSON' }}</el-button>
                <el-input v-model="queryForm.query_field_json" placeholder="接口参数" type="textarea" v-if="showJsonFormat"
                    :rows="textareaRows"></el-input>
                <el-table v-else :data="queryForm.query_field_list" border fit highlight-current-row>
                    <el-table-column align="center" label="参数名称" value="">
                        <template slot-scope="{row}">
                            <span>{{ row.interface_para_name }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="参数编码" value="">
                        <template slot-scope="{row}">
                            <span>{{ row.interface_para_code }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="参数数值" value="">
                        <template slot-scope="{row}">
                            <!-- todo： 修改为行内编辑的样式  -->
                            <el-input :placeholder="row.interface_para_code"
                                v-model="queryForm.query_para_value[row.interface_para_code]"></el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
        </el-form>


        <el-button @click="queryData({ env_type: 0 })" type="text" size="small">查询测试环境</el-button>
        <el-button @click="queryData({ env_type: 1 })" type="text" size="small">查询生产环境</el-button>
        <el-button @click="exportData({ env_type: 0 })" type="text" size="small">测试导出</el-button>
        <el-button @click="exportData({ env_type: 1 })" type="text" size="small">生产导出</el-button>

        <div v-loading="queryLoading || downloadLoading">
            <el-alert v-if="this.page.total > 0" :title="`共有${this.page.total}条数据`" type="success" show-icon center
                close-text="关闭" :closable="true"></el-alert>

            <el-alert v-if="errorMsg.error" :title="errorMsg.msg" type="error" show-icon center close-text="关闭"
                :closable="true"></el-alert>

            <el-table v-if="visiable" :data="tableData" border highlight-current-row style="width: 100%">
                <el-table-column align="center" v-for="item in columns" :key="item.position"
                    :label="item.paraDesc ? item.paraDesc : item.paraName" :show-overflow-tooltip="true" :min-width="100">
                    <template slot-scope="{row}">
                        <span>{{ row[item.paraCode] }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="page.total > 0" :total="page.total" :page.sync="page.page_no"
                :limit.sync="page.page_size" @pagination="nextPage()" />

        </div>

    </div>
</template>

<script>
import { getReportData, getInterfaceFields } from '@/api/report'
import { queryData } from '@/api/sqlquery';

import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'
import XLSX from 'xlsx'

export default {
    props: {
        id: {
            type: String,
        },
        code: {
            type: String
        },
        codeEditable: {
            type: Boolean
        }
    },
    components: {
        Pagination
    },
    data() {
        return {
            tableShowLimit: 100,
            visibleData: [],
            columns: [],
            dataList: [],
            totalDataList: [],
            textareaRows: 5,
            // total: 0,
            // page: 1,
            // pageQueryEnv:0,
            // limit: 30,
            page: {
                env_type: 0,
                page_no: 1,
                page_size: 30,
                total: 0
            },
            tableData: [],
            visiable: false,
            showJsonFormat: false,
            queryLoading: false,
            downloadLoading: false,
            exportOptions: {
                filename: 'test.xlsx',
                autoWidth: true,
                bookType: 'xlsx'
            },
            errorMsg: {
                error: false,
                msg: ''
            },
            queryForm: {
                code: this.code,
                query_field_json: '',
                query_field_list: [],
                query_para_value: {}
            }
        }
    },
    watch: {
        showJsonFormat: function (val) {
            if (val) {
                this.queryForm.query_field_json = JSON.stringify(this.queryForm.query_para_value, null, 2)
                // console.log("query_field_json",this.queryForm.query_field_json)
            } else {
                this.queryForm.query_para_value = JSON.parse(this.queryForm.query_field_json)
                // console.log("query_para_value",this.queryForm.query_para_value)
            }
        }
    },
    mounted() {
        this.getInterfaceQueryInfo()
        // this.updateVisibleData()
    },
    methods: {
        getInterfaceQueryInfo() {
            getInterfaceFields({ interface_id: this.id, interface_para_type: '1' }).then(response => {
                this.queryForm.query_field_list = response.data
                this.queryForm.query_field_json = '{' + this.queryForm.query_field_list.map(e => `"${e.interface_para_code}":""`).join(',') + '}'
                this.queryForm.query_para_value = JSON.parse(this.queryForm.query_field_json)
                // console.log(this.queryForm.query_field_json)
            })
        },
        queryData(data) {
            this.reset()
            let interface_code = this.queryForm.code
            // 只拷贝数值，不修改被引用的对象值
            let payload = this.showJsonFormat ? JSON.parse(this.queryForm.query_field_json) : { ... this.queryForm.query_para_value }
            // console.log(this.showJsonFormat, payload)
            payload = Object.assign(payload, {
                "export_type": "1",
                "operate_type": "1",
                "page_no": this.page.page_no,
                "page_size": this.page.page_size
            })
            this.queryLoading = true

            getReportData({ interface_code, payload, env_type: data.env_type }).then(response => {
                const res = response.data
                try {
                        if (res.code == '-1') {
                            this.errorMsg.error = true
                            this.errorMsg.msg = res.message
                        } else {
                            const property = res.property
                            this.columns = this.sortColumns(property)
                            if (res.isPaging == '1') {
                                this.dataList = res.data.list
                                this.page.total = res.data.total
                                this.tableData = this.dataList
                            } else {
                                this.dataList = res.data
                                this.page.total = this.dataList.length
                                this.tableData = this.dataList.slice((this.page.page_no - 1) * this.page.page_size, this.page.page_no * this.page.page_size)
                            }

                            if (res.isTotal == '1') {
                                this.totalDataList = res.totaldata
                                this.tableData = this.tableData.concat(this.totalDataList)
                            }
                            this.visiable = true
                        }
                        this.queryLoading = false
                        this.page.env_type = data.env_type
                } catch (e) {
                    this.errorMsg.error = true
                    this.errorMsg.msg = "接口返回数据失败"
                } finally {
                    this.queryLoading = false
                }
            }
            ).finally(() => {
                this.queryLoading = false
            })
        },
        exportData(data) {
            let interface_code = this.queryForm.code
            let payload = this.showJsonFormat ? JSON.parse(this.queryForm.query_field_json) : { ... this.queryForm.query_para_value }
            payload = Object.assign(payload, {
                "export_type": "2",
                "operate_type": "2"
            })
            this.downloadLoading = true
            // this.pageQueryEnv = data.env_type
            getReportData({ interface_code, payload, env_type: data.env_type }).then(response => {
                try {
                    if (response.data.code == '-1') {
                        this.errorMsg.error = true
                        this.errorMsg.msg = response.data.message
                    } else {
                        const row = response.data.data
                        if (response.data.isTotal == '1') {
                            row.push(...response.data.totaldata)
                        }
                        const interfaceName = response.data.interfaceName
                        this.total = row.length
                        const tHeader = this.sortColumns(response.data.property, 2)
                        const tHeaderCode = tHeader.map(col => col.paraCode)
                        const worksheet = XLSX.utils.json_to_sheet(row, { header: tHeaderCode })
                        const workbook = XLSX.utils.book_new();
                        const tHeaderDesc = []
                        tHeaderDesc.push(tHeader.map(col => col.paraDesc))
                        XLSX.utils.sheet_add_aoa(worksheet, tHeaderDesc)
                        XLSX.utils.book_append_sheet(workbook, worksheet);
                        const export_time = parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')
                        XLSX.writeFile(workbook, `${interfaceName}-${export_time}.xlsx`, { compression: true });
                    }
                    this.visiable = true
                    this.downloadLoading = false
                } catch (e) {
                    this.errorMsg.error = true
                    this.errorMsg.msg = '导出失败'
                } finally {
                    this.downloadLoading = false
                }
            }).finally(() => {
                this.downloadLoading = false
            })
        },
        sortColumns(columns, flag = 1) {
            return Object.entries(columns).filter(column => {
                if (flag == '1') {
                    // 可查询
                    return column[1].showFlag == '1'
                } else {
                    // 导出
                    return column[1].exportFlag == '1'
                }
            }).sort(([k1, v1], [k2, v2]) => {
                return v1.position - v2.position
            }).map(o => o[1])
        },
        reset() {
            this.errorMsg.error = false
            this.visiable = false
        },
        nextPage() {
            if (this.dataList.length > this.page.page_size) {
                this.tableData = this.dataList.slice((this.page.page_no - 1) * this.page.page_size, this.page.page_no * this.page.page_size)
                this.tableData = this.tableData.concat(this.totalDataList)
            } else {
                this.queryData({ env_type: this.page.env_type })
            }
        }
    }
}
</script>

<style>
.scroll-container {
    height: 500px;
    overflow-y: auto;
    position: relative;
}

.table-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
}
</style>